<?php

namespace frontend\models;

use Yii;
use yii\db\ActiveRecord;
use yii\db\Query;
use yii\behaviors\TimestampBehavior;
use yii\db\Exception;
/**
 * This is the model class for table "Banner".
 *
 */
class Banner extends ActiveRecord
{

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%banner}}';
    }



    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }
    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['title','pic','url'], 'trim'],
            [['id','title','pic','status','url'], 'required', 'message'=>'{attribute}不能为空'],
            [['id','status'], 'match', 'pattern' => '/^[1-9][0-9]*$/','message'=>'{attribute}值无效'],
            [['title'], 'unique', 'message'=>'{attribute}已存在','on' => ['create']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id'=>'banner id',
            'title'=>'banner标题',
            'pic'=>'banner图片',
            'url' => 'banner跳转链接',
            'status'=>'banner状态',
        ];
    }



    public function scenarios()
    {
        return [
            'default' => [
                'id',
                'title',
                'pic',
                'url',
                'created_at',
                'updated_at',
                'deleted_at',
            ],
            'create' => [
                'title',
                'pic',
                'url',
                'status',
                'created_at',
                'updated_at',
                'deleted_at',
            ],
            'update_status' => [
                'id',
            ],
            'delete_banner' => [
                'id',
            ],
            'update' => [
                'id',
                'title',
                'pic',
                'url',
                'status',
                'created_at',
                'updated_at',
                'deleted_at',
            ],
        ];
    }



    /**
     * 获取banner列表
     * @param $params
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getBannerList($params){
        if(!empty($params['title'])){
            $condition= ['and',['like','title',trim($params['title'])],['deleted_at'=>null]];
        }else{
            $condition = ['deleted_at'=>null];
        }
        $list = (new Query())
            ->select('id,title,url,status,pic,FROM_UNIXTIME(created_at) as create_time')
            ->from('banner')
            ->where($condition)
            ->orderBy('id desc')
            ->all();
        return empty($list)?array():$list;

    }


    /**
     * 新增banner
     * @param $param
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function addBannerInfo($param){
        $t = static::getDb()->beginTransaction();
        try {
            $model = new self();
            $model->scenario = 'create';
            unset($param['id']);
            $model->setAttributes($param, false);
            if (!$model->save()) {
                $t->rollBack();
                return array('error'=>'操作失败');
            }else{
                $model->refresh();
                $t->commit();
                return array('error'=>'');
            }
        }catch (Exception $e) {
            $t->rollback();
            return array('error'=>'操作失败');
        }

    }


    /**
     * 编辑banner
     * @param $param
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function editBannerInfo($param){
        $t = static::getDb()->beginTransaction();
        try {
            $model = static::findOne(['id' =>$param['id']]);
            if(empty($model)) return array('error'=>'未查询到相关信息');
            if(!empty($param['title'])) {
                $have_projectname = $this->find()->where(['title' => $param['title']])->andWhere(['<>', 'id', intval($param['id'])])->asArray()->one();
                if (!empty($have_projectname)) return array('error' => '标题已存在');
            }
            unset($param['id']);
            $model->setAttributes($param, false);
            if (!$model->save()) {
                $t->rollBack();
                return array('error'=>'操作失败');
            }else{
                $model->refresh();
                $t->commit();
                return array('error'=>'');
            }
        }catch (Exception $e) {
            $t->rollback();
            return array('error'=>'操作失败');
        }

    }


    /**
     * 删除banner
     * @param $param
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function deleteBannerInfo($param){
        $t = static::getDb()->beginTransaction();
        try {
            $model = static::findOne(['id' =>$param['id']]);
            if(empty($model)) return array('error'=>'未查询到相关信息');
            if($model->status == 3) return array('error'=>'');
            unset($param['id']);
            $data['status']=3;
            $data['deleted_at'] = time();
            $model->setAttributes($data, false);
            if (!$model->save()) {
                $t->rollBack();
                return array('error'=>'操作失败');
            }else{
                $model->refresh();
                $t->commit();
                return array('error'=>'');
            }
        }catch (Exception $e) {
            $t->rollback();
            return array('error'=>'操作失败');
        }

    }



    /**
     * 批量删除banner
     * @param $param
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function batchDelBannerInfo($param){
        $t = static::getDb()->beginTransaction();
        try {
            $ids=explode(',',$param['ids']);
            if(empty($ids)) return array('error'=>'参数错误');
            $res=$this::updateAll(['status' => 3,'deleted_at'=>time()], ['in','id' ,$ids]);
            if (!$res) {
                $t->rollBack();
                return array('error'=>'操作失败');
            }else{
                $this->refresh();
                $t->commit();
                return array('error'=>'');
            }
        }catch (Exception $e) {
            $t->rollback();
            return array('error'=>'操作失败');
        }

    }



}
